
package com.evl.core.support;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ConnectException;
import java.net.URL;

import javax.net.ssl.HttpsURLConnection;

import org.apache.log4j.Logger;

public class WeiXinKit {
	
    private static Logger log = Logger.getLogger(WeiXinKit.class);
	
	 public static String httpRequest(String requestUrl, String requestMethod, String outputStr)
	  {
	    StringBuffer buffer = new StringBuffer();
	    try
	    {
	     /* TrustManager[] tm = { new MyX509TrustManager() };
	      SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
	      sslContext.init(null, tm, new SecureRandom());

	      SSLSocketFactory ssf = sslContext.getSocketFactory();*/

	      URL url = new URL(requestUrl);
	      HttpsURLConnection httpUrlConn = (HttpsURLConnection)url.openConnection();
//	      httpUrlConn.setSSLSocketFactory(ssf);

	      httpUrlConn.setDoOutput(true);
	      httpUrlConn.setDoInput(true);
	      httpUrlConn.setUseCaches(false);

	      httpUrlConn.setRequestMethod(requestMethod);

	      if ("GET".equalsIgnoreCase(requestMethod)) {
	        httpUrlConn.connect();
	      }

	      if (outputStr != null) {
	        OutputStream outputStream = httpUrlConn.getOutputStream();

	        outputStream.write(outputStr.getBytes("UTF-8"));
	        outputStream.close();
	      }

	      InputStream inputStream = httpUrlConn.getInputStream();
	      InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
	      BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

	      String str = null;
	      while ((str = bufferedReader.readLine()) != null) {
	        buffer.append(str);
	      }
	      bufferedReader.close();
	      inputStreamReader.close();

	      inputStream.close();
	      inputStream = null;
	      httpUrlConn.disconnect();
	    } catch (ConnectException ce) {
	    	log.error("Weixin server connection timed out.");
	    } catch (Exception e) {
	    	log.error("https request error:{}", e);
	    }
	    return buffer.toString();
	  }
}
